<?php
/**
 * - check if there already is a sync set on this account
 * - if there is
 * 		- set user id to device in devices
 * 		- let device know it should retrieve sync data (also send user_id to device)
 * - else
 * 		- create a new entry in users
 * 		- request device to upload sync data
 */
$input = $_POST;
if (!isset($input['deviceId'])
		|| !isset($input['email'])) {
	header("HTTP/1.1 400 Bad Request");
	exit;
}
$deviceId = $input['deviceId'];
$email = $input['email'];
require_once 'db.inc.php';

if (mysql_num_rows(mysql_query("SELECT * FROM ".TABLE_PREFIX."devices WHERE deviceId = '$deviceId'")) == 0) {
	header("HTTP/1.1 401 Device Not Registered");
	exit;
}

header("Content-Type: application/json");
$result = mysql_query("SELECT * FROM ".TABLE_PREFIX."users WHERE email = '$email'");
if (mysql_num_rows($result) == 1) {
	$userId = mysql_result($result, 0, 'id');
	mysql_query("UPDATE ".TABLE_PREFIX."devices set user = $userId WHERE deviceId = '$deviceId'");
	echo json_encode(array("user_id" => $userId, "action_required" => "request_data"));
} else {
	mysql_query("INSERT INTO ".TABLE_PREFIX."users (email) VALUES ('$email');");
	$userId = mysql_insert_id();
	mysql_query("UPDATE ".TABLE_PREFIX."devices SET user = $userId WHERE deviceId = '$deviceId'");
	echo json_encode(array("user_id" => $userId, "action_required" => "push_data"));
}
?>